﻿using System.Collections.Generic;

public class GlobalMsg : Singleton<GlobalMsg>
{
    public delegate void ListenerDelegate(params object[] inParams);
    private Dictionary<EMessage, List<ListenerDelegate>> _dicListener = null;

    private GlobalMsg()
    {
        _dicListener = new Dictionary<EMessage, List<ListenerDelegate>>();
    }

    public void AddObserver(EMessage inType, ListenerDelegate inDelegate)
    {
        List<ListenerDelegate> entry = null;
        _dicListener.TryGetValue(inType, out entry);

        if(null == entry) {
            entry = new List<ListenerDelegate>();
            _dicListener[inType] = entry;
        }
        if (entry.Contains(inDelegate)) {
            UnityEngine.Debug.LogError("GlobalMsg: delegate is already exists, repeated addition...");
        } else {
            entry.Add(inDelegate);
        }
    }

    public void RemoveObserver(EMessage inType, ListenerDelegate inDelegate)
    {
        List<ListenerDelegate> entry = null;
        _dicListener.TryGetValue(inType, out entry);

        if (null == entry || !entry.Contains(inDelegate)) {
            UnityEngine.Debug.LogError("GlobalMsg: don't have such listener...");
        } else {
            entry.Remove(inDelegate);
        }
    }

    public void SendMsg(EMessage inType, params object[] inParams)
    {
        if (_dicListener.ContainsKey(inType)) {
            for(int i=0; i<_dicListener[inType].Count; i++) {
                _dicListener[inType][i](inParams);
            }
        }
    }
}

